package cn.sylinx.hbatis.plugin.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.sylinx.hbatis.io.ClasspathResourceScanner;
import cn.sylinx.hbatis.log.GLog;
import cn.sylinx.hbatis.plugin.IPlugin;

public class ModelPreloadPlugin implements IPlugin {

	/**
	 * 扫描包路径
	 */
	private List<String> scanPackageList;

	/**
	 * 指定类名称
	 */
	private Set<String> clzSets;

	// 对象模型字段映射类
	private String acmStrategyClass;

	public List<String> getScanPackageList() {
		return scanPackageList;
	}

	public void setScanPackageList(List<String> scanPackageList) {
		this.scanPackageList = scanPackageList;
	}

	public String getAcmStrategyClass() {
		return acmStrategyClass;
	}

	public void setAcmStrategyClass(String acmStrategyClass) {
		this.acmStrategyClass = acmStrategyClass;
	}

	public Set<String> getClzSets() {
		return clzSets;
	}

	public void setClzSets(Set<String> clzSets) {
		this.clzSets = clzSets;
	}

	@Override
	public boolean start(Object... objects) {

		if (clzSets == null) {
			clzSets = new HashSet<String>();
		}

		if (acmStrategyClass != null) {
			// 设置全局字段映射策略
			ModelConst.ME.setAcmStrategy(acmStrategyClass);
		}

		if (scanPackageList != null && !scanPackageList.isEmpty()) {

			for (String scanOnePackage : scanPackageList) {
				scanOnePackage(scanOnePackage);
			}
		}

		ModelCacheManager.get().init(clzSets);

		return true;
	}

	private void scanOnePackage(String scanPackage) {

		GLog.debug("扫描包[{}]...", scanPackage);
		ClasspathResourceScanner cp = new ClasspathResourceScanner(scanPackage, ".class", true);
		List<String> rList = null;
		try {
			rList = cp.getResourceNameList();
		} catch (Exception e) {
		}

		if (rList == null) {
			rList = new ArrayList<String>();
		}

		for (String rs : rList) {
			String pt1 = rs.replaceAll("/", "\\.");
			int index = pt1.lastIndexOf(".class");
			pt1 = pt1.substring(0, index);
			
			clzSets.add(pt1);
		}

	}

	@Override
	public boolean stop() {
		return true;
	}

}
